package com.sssre.lttcloud.auth.controller;

import com.sssre.lttcloud.api.dto.LoginRequest;
import com.sssre.lttcloud.auth.entity.AuthUser;
import com.sssre.lttcloud.auth.service.UserService;
import com.sssre.lttcloud.common.result.Result;
import com.sssre.lttcloud.common.result.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/auth")
@CrossOrigin
public class AuthController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result login(@Valid @RequestBody LoginRequest loginRequest) {
        return userService.login(loginRequest.getUsername(), loginRequest.getPassword());
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result register(@Valid @RequestBody AuthUser user) {
        return userService.register(user);
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result logout(@RequestHeader("Authorization") String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        return userService.logout(token);
    }

    /**
     * 刷新token
     */
    @PostMapping("/refresh")
    public Result refreshToken(@RequestParam String refreshToken) {
        return userService.refreshToken(refreshToken);
    }

    /**
     * 验证token
     */
    @GetMapping("/validate")
    public Result validateToken(@RequestHeader("Authorization") String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        boolean isValid = userService.validateToken(token);
        return isValid ? Result.success() : Result.failed(ResultCode.UNAUTHORIZED, "Token无效");
    }
} 